#pragma once

#include <iostream>
#include <string>
#include <functional>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"
#include "InetAddr.hpp"

using namespace LogModule;
using func_t = std::function<void(int, const std::string &, InetAddr &)>;

class UdpServer
{
public:
    UdpServer(uint16_t port, func_t func)
        : _port(port), _func(func), _sockfd(-1), _isrunning(false)
    {
    }

    void Init()
    {
        // 1.创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket error";
            exit(1);
        }
        LOG(LogLevel::INFO) << "socket success,sockfd:" << _sockfd;

        // 2.绑定端口号
        struct sockaddr_in local;
        bzero(&local, sizeof(local)); // 填充0
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;
        // 当然这里也可以直接调用我们的InetAddr
        // InetAddr addr("0",_port);
        // addr.NetAddr();

        int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind error";
            exit(2);
        }
        LOG(LogLevel::INFO) << "bind success,sockfd:" << _sockfd;
    }

    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            // 服务端的工作就是接收客户端的信息，然后对信息进行处理
            char buffer[1024];
            struct sockaddr_in peer; // 存储发来信息的客户端的IP+Port
            socklen_t len = sizeof(peer);
            ssize_t s = recvfrom(_sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&peer, &len);
            if (s > 0)
            {
                buffer[s] = 0;
                InetAddr client(peer);
                _func(_sockfd,buffer,client);//在该方法里面将消息转发给其他客户
            }
        }
    }

    ~UdpServer() {}

private:
    int _sockfd;
    uint16_t _port; // 服务端只需要绑定端口号即可
    bool _isrunning;
    func_t _func; // 服务端的回调函数，用于处理收到的数据
};